// Licensed to Cloudera, Inc. under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

(function ($) {
  $.fn.textSqueezer = function (options) {
    var settings = $.extend({
         maxIterations : 40,
         decimalPrecision: -1
      }, options),
        iters = 0,
        startSqueeze = function (el) {
          $(el).removeAttr("style");
          if (settings.decimalPrecision > -1){
            var _n = parseFloat($(el).text());
            if ($.isNumeric(_n)){
              $(el).text(+_n.toFixed(settings.decimalPrecision));
            }
          }
          iters = 0;
          squeeze(el);
        },
        squeeze = function (el) {
          iters++;
          var $el = $(el);
          var _fontStep = 2;
          // limit on iters to avoid stackoverflow for very long strings
          if (iters < settings.maxIterations && $el.width() > $el.parent().width()) {
            $el.css('font-size', (($el.css('font-size').substr(0, 2) - _fontStep)) + 'px').css('line-height', (($el.css('font-size').substr(0, 2))) + 'px');
            squeeze(el);
          }
        }

    return this.each(function () {
      var that = this;
      $(window).resize(function () {
        startSqueeze(that);
      });
      $(this).on("redraw", function () {
        startSqueeze(that);
      });
      startSqueeze(this);
    });
  };
}(jQuery));